File Input
Often, a program needs to read input from a file and perform some operation(s) on that input and then output the information to the user or to another file. This lesson will show you how to open a file and read the data into variables in your program so that your program can perform additional processing on the data.
The FORTRAN commands that are used for this are: OPEN
,
CLOSE
, READ
, and WRITE
.
The OPEN
function creates (opens) a link to an external data file.
The CLOSE
function removes (closes) a link to an external data file.
The READ
function copies data from an input stream to a program variable.
The WRITE
function copies data from a program variable to an output stream.
The syntax for opening a file is easiest when the file is in the current directory.
But, this is not a requirement since all file systems have a way
to reference files in other locations.
The OPEN
command accepts several arguments. Though, not all are required.
- [UNIT=] an integer 1-99 that is used to identify to which input stream the file is attached.
- FILE= - a text string or variable with a text string that specifies which file to open.
- ERR= - a label indicating where to go in the event an error occurs.
- IOSTAT= - an integer variable that receives the I/O status identifier. The value of this variable will be zero if there were no errors opening the file.
- STATUS= - a character string that describes the previous status (NEW,OLD,SCRATCH) of the file being opened.
A simple example
This example opens a file that has three data values on one line and reads the data into the variables, i, x, and y.
open( 10, FILE='temp.dat') read(10,900) i,x,y 900 format(I4,2F6.1) close(10)
The first line opens the file and assigns the unit number 10 to that file. The next line reads the first line of the file into the variables, x, y, and z according to the format described in the third line (900). i is read as an integer of width 4 digits, then x an y are each read in as 6 digit floating point values with 1 digit to the right of the decimal. So a value of 1234.5 would be accepted in this form.